const { ipcRenderer } = window.require('electron');
import React from 'react';

let shareInited = false;
let uid = 1;

let Share = {};

function UUID() {
    return ++uid;
}
let observer = {
    observers: [],
};

ipcRenderer.on('sys-get-share', (event, arg) => {
   Share = arg;
   console.log('sys-get-share', arg);
   for (let i = 0; i < observer.observers.length; i++) {
       observer.observers[i].callback && observer.observers[i].callback(observer.observers[i].key, Share);
   }
});

ipcRenderer.invoke('user-get-share')
    .then((res) => {
        Share = res;
        console.log('user-get-share', res);
        for (let i = 0; i < observer.observers.length; i++) {
            observer.observers[i].callback && observer.observers[i].callback(observer.observers[i].key, Share);
        }
    });

function dispatch(option) {
    const { type, payload } = option;
    const modelAndReducer = type.split('/');
    ipcRenderer.invoke('user-proxy-share', {
        model: modelAndReducer[0],
        reducer: modelAndReducer[1],
        arguments: payload
    })
}

function listenShare() {
    observer.observe = function (key, callback) {
        const index = observer.observers.findIndex(vo => vo.key === key);
        if (index >= 0) {
            observer.observers[index] = {
                key,
                callback,
            };
        } else {
            observer.observers.push({
                key,
                callback,
            });
        }
    }
    observer.unobserve = function ( key) {
        const index = observer.observers.findIndex(vo => vo.key === key);
        (index >= 0) && observer.observers.splice(index, 1);
    };
}


/**
 * 监听共享属性
 * @param key
 */
function connect(func) {
    return (Wrapper) => {
        return class extends React.Component {
            constructor(props) {
                super(props);
                this.state = func({ ...Share, dispatch });
                this.uuid = UUID();
            }

            componentWillMount() {
                //XUE.observe.watch(store, Share[store]);
                observer.observe(
                    `ob$${this.uuid}`,
                    (key, attr, data) => {
                        if (key !== `ob$${this.uuid}`) {
                            return;
                        }
                        this.setState({
                            ...func({ ...Share, dispatch })
                        })
                    }
                )
            }

            componentWillUnmount() {
                observer.unobserve(`ob$${this.uuid}`);
            }

            render() {
                return <Wrapper { ...this.props } { ...this.state } />
            }
        }
    }
}


export function injectShare(XUE) {
    listenShare();
    XUE.share = {
        connect,
        dispatch
    }
}

